from datetime import datetime, time

import pandas as pd
from fastapi import APIRouter
import akshare as ak

import threading
from starlette.responses import HTMLResponse, PlainTextResponse, Response

from model.LstmUtil import prediction
from utils.data_source import update, query, mysql_db, engine
from utils.data_utils import data_update, update_analysis, init_pram, suggest, suggest_hc

router = APIRouter(
    prefix='/user',
    tags=['用户相关']
)


@router.get("/lstm")
async def get_server_stats():
    thread = threading.Thread(target=prediction)
    thread.start()  # 启动线程
    # thread.join()
    return HTMLResponse()


@router.get("/update_day_his")
async def get_server_stats():
    thread = threading.Thread(target=update_day_his)
    thread.start()  # 启动线程
    # thread.join()
    return HTMLResponse()

@router.get("/stats")
async def get_server_stats():
    return PlainTextResponse(ak.index_stock_cons_csindex(symbol="000300")[['成分券代码', '成分券名称']] \
                             .to_csv(index=False, encoding='utf-8', sep='\t'))


@router.get("/company_list")
async def company_list():
    company_list = ak.stock_zh_a_spot_em()
    company_list = company_list[company_list['最新价'] > 2]
    company_list = company_list[company_list['换手率'] > 0]
    company_list = company_list[company_list['市盈率-动态'] > 0]
    company_list = company_list[~company_list['名称'].str.contains('ST|退|XD|N')]
    company_list = company_list[company_list['代码'].str.startswith(('00', '60'))]
    company_list = company_list.sort_values(by='市盈率-动态', ascending=True)
    # for row in company_list.itertuples():
    # ak.stock_zygc_ym(symbol=row.代码)
    return Response(company_list.to_csv(index=False, encoding='utf-8', sep=','), media_type="text/plain")


def update_day_his():
    sh = ak.stock_sh_a_spot_em()
    sz = ak.stock_sz_a_spot_em()
    company_list = pd.concat([sh, sz])
    company_list = company_list[company_list['最新价'] > 5]
    company_list = company_list[company_list['最新价'] < 50]
    # company_list = company_list[company_list['市盈率-动态'] > 0]
    # company_list = company_list[company_list['市盈率-动态'] < 50]
    company_list = company_list[company_list['总市值'] < 100000000000]
    company_list = company_list[~company_list['名称'].str.contains('ST|退|XD|N|C')]
    # company_list = company_list[company_list['名称'].isin(ggx)]
    company_list = company_list[company_list['代码'].str.startswith(('00', '60'))]
    company_list = company_list.sort_values(by='成交额', ascending=False)[0:300]
    company_list.to_sql('company', con=engine(), if_exists='replace', index=False)
    # 更新日线
    update(f"""truncate world.history""")
    for row in company_list.itertuples():
        data_update(row.代码, row.名称)
    # 清理数据长度不够的数据
    update(
        f"""delete from company where 代码 in (select symbol from (select count(1) cou,symbol from world.history group by symbol) a where a.cou !=(select max(cou) from (select count(1) cou from world.history group by symbol)a))""")
    update(
        f"""delete from world.history where symbol in (select symbol from (select count(1) cou,symbol from world.history group by symbol) a where a.cou !=(select max(cou) from (select count(1) cou from world.history group by symbol)a))""")
    print("update_day_his ,finished")


def update_min_his():
    company_list = ak.stock_zh_a_spot_em()
    symbols = query("""select distinct symbol from history""")["symbol"].tolist()
    company_list = company_list[company_list['代码'].isin(symbols)]
    company_list = company_list[company_list['换手率'] > 0]
    args = list()
    update(f"""delete from world.history where data >= '{datetime.date.today().__format__("%Y%m%d")}'""")
    for row in company_list.itertuples():
        args.append((str(row.代码), str(row.名称), datetime.date.today().__format__("%Y%m%d"), str(row.今开),
                     str(row.最新价), str(row.最高), str(row.最低), str(row.成交量), str(row.成交额), str(row.振幅),
                     str(row.涨跌幅), str(row.涨跌额), str(row.换手率)))
    con = mysql_db()
    with con.cursor() as cursor:
        sql = f"""INSERT INTO world.history(symbol,name,data,open,close, high, low,cjl,cje, zf,zdf,zde,hsl) 
            VALUES (%s,%s,%s,%s,%s, %s, %s,%s,%s,%s,%s,%s,%s)"""
        cursor.executemany(query=sql, args=args)
        con.commit()


# 抄底均线战法
def cdjx():
    print(datetime.datetime.now())
    update_analysis(analysis_tail=False)
    params = init_pram()
    suggest(params)
    print(datetime.datetime.now())
    while True:
        today = datetime.datetime.now().__format__("%H%M")
        # 盘中决策
        # if 930 < int(today) < 1130 or 1300 < int(today) < 1455:
        #     suggest(params)
        # 股票买入收盘价
        if '1454' == today:
            update_analysis(analysis_tail=False)
            params = init_pram()
            suggest(params)
            time.sleep(45)
        # 修正最终数据
        if '1503' == today:
            update_analysis(analysis_tail=True)
            time.sleep(45)
        time.sleep(15)


# 快速跟风算法
def ksgf():
    while True:
        today = datetime.datetime.now().__format__("%H%M")
        print(int(today))
        if 930 < int(today) < 1130 or 1300 < int(today) < 1450:
            update_min_his()
            suggest_hc()
        # 修正最终数据
        if 1500 < int(today) < 1510:
            update_day_his()
            time.sleep(600)
        time.sleep(60)


